<?php

declare(strict_types=1);
namespace app\middleware;

use think\Request;
use think\exception\HttpException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use app\api\logic\UserLogic; // 修改为适用于API模块的逻辑处理类

class ApiJwtMiddleware
{
    public function handle(Request $request, \Closure $next)
    {
        try {
            $authHeader = $request->header('Authorization');
            if (!$authHeader) {
                return json(['code' => 500, 'msg' => 'Access token required'], 500);
            }

            if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
                $token = $matches[1];
            } else {
                throw new HttpException(401, 'Token not found');
            }
            $secretKey = env('JWT.JWT_API_KEY', '');
            $decoded = JWT::decode($token, new Key($secretKey, 'HS256'));

            $user = new UserLogic();
            $userInfo = $user->getUserInfo($decoded->data->id);
            if ($userInfo['error']) {
                throw new HttpException(401, '用户信息不存在');
            }

            $request->jwt = $decoded;
            $request->userInfo = $userInfo['data'];

            return $next($request);
        } catch (\Exception $e) {
            return json(['code' => 401, 'msg' => $e->getMessage()], 401);
        }
    }
}
